package com.agilestudio.ifinance.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.agilestudio.ifinance.entity.IdEntity;
import com.agilestudio.ifinance.entity.account.Menu;
import com.agilestudio.ifinance.service.account.AccountService;

public abstract class AbstractController {

	@Autowired
	protected AccountService accountService;

	@Autowired
	protected Validator validator;

	protected Logger log = LoggerFactory.getLogger(getClass());

	protected void initMenus(Map<String, Object> map) {
		List<Menu> allMenus = accountService.getOrganizedMenus();
		map.put("menus", allMenus);
		return;
	}

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.setDisallowedFields("create*");
		binder.setDisallowedFields("update*");
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}

	protected void validate(IdEntity e) {
		Set<ConstraintViolation<IdEntity>> set = validator.validate(e);
		for (ConstraintViolation<IdEntity> violation : set) {
			String propertyPath = violation.getPropertyPath().toString();
			String message = violation.getMessage();
			log.error("invalid value for: '" + propertyPath + "': " + message);
		}
	}

	public Validator getValidator() {
		return validator;
	}

	public void setValidator(Validator validator) {
		this.validator = validator;
	}

}
